/** 
* @Author: yanyanru
* @Date: 2018/4/10
* @description: 人物列表
*/
<template>
  <div class="cms-detail-box p-20">
      <div class="custom-title">
          <h3>基本信息
            <span>最后更新时间 {{ person.modifyTime | cmsMoment }}</span>
          </h3>
          <div class="pull-right">
              <detailStateBtn
                class="inline-block m-r-10" 
                @setState="setState"
                :infoStatus="person.infoStatus"
              />
              <el-button type="primary" @click="close">关闭</el-button>
          </div>
      </div>
      <el-form labelWidth='90px' ref='basicForm' :rules="rules" :model="person">
        <el-row>
          <el-col :span="12">
            <el-form-item label='中文名称' required prop="cnName">
              <el-autocomplete
                class="w-100"
                :maxlength="50"
                v-model="person.cnName"
                :fetch-suggestions="getSearchTitle"
                placeholder="请输入内容"
                :trigger-on-focus="false"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>  
            <el-form-item label='英文名称' prop="enName">
              <el-input v-model='person.enName' :maxlength="50"></el-input>
            </el-form-item>
             <el-row>
                <el-col :span="24">
                    <el-form-item label="人物类型" required prop="personTypes">
                        <el-checkbox-group v-model="personTypesList" @change="changePersonType">
                            <el-checkbox 
                              v-for="item in initView.personageTypes" 
                              :label="item.dictValue-0" 
                              :value="item.dictName"
                              :key="item.dictValue">{{item.dictName}}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                    <el-form-item label="性别">
                        <el-select placeholder="请选择" v-model="person.sex">
                            <el-option v-for='item in initView.sex'
                                        :key='item.dictValue'
                                        :value='item.dictValue-0'
                                        :label="item.dictName" >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
             <el-row>
                <el-form-item label="籍贯">
                    <el-cascader
                    style="width:300px"
                    v-model="area"
                    :options="areaList"
                    :filterable="true"
                    :clearable="true" />
                  </el-form-item>
            </el-row>
            <el-row>
                <el-form-item label="手机">
                  <el-row v-for="(item,index) in personContactsTel" :key="index">
                    <el-input style="width:90%" v-model="item.contactValue" @blur="changeTel(personContactsTel,item.contactValue,index)"></el-input>
                    <button type="button" class="custom-btn custom-btn-round" @click="addTel" v-if="index == 0">
                      <i class="fa fa-plus"></i>
                    </button>
                    <button type="button" class="custom-btn custom-btn-round" @click="deleteTel(index)" v-else>
                      <i class="fa fa-remove"></i>
                    </button>
                  </el-row> 
                </el-form-item>
            </el-row>
            <el-row>
                <el-form-item label="邮箱">
                  <el-row v-for="(item,index) in personContactsMail" :key="index">
                    <el-input style="width:90%" v-model="item.contactValue" type="email" @blur="changeMail(personContactsMail,item.contactValue,index)"></el-input>
                    <button type="button" class="custom-btn custom-btn-round" @click="addMail" v-if="index == 0">
                      <i class="fa fa-plus"></i>
                    </button>
                    <button type="button" class="custom-btn custom-btn-round" @click="deleteMail(index)" v-else>
                      <i class="fa fa-remove"></i>
                    </button>
                  </el-row> 
                </el-form-item>
            </el-row>
            <el-row>
                <el-form-item label="学历">
                    <el-select placeholder="请选择" v-model='person.education'>
                        <el-option v-for='item in initView.personEducation'
                            :key='item.dictValue'
                            :value='item.dictValue-0'
                            :label="item.dictName">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-row>
            <el-row>
                <el-form-item label="头像" >
                     <logoImg
                      ref="logoImg"
                      @onSuccess="onSuccess"
                      :src='person.ossPhotoUrl' />
                </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="12">
            <!-- 标签 -->
            <cmsTag 
              :comTagDtoList="comTagDtoList" 
              :cvIndustryValue="cvIndustryValue" 
              :shouwAddTag="true"
               @tagPass='tagPass' 
               :businessId="itemId"
               :businessType="15"
               ref="tag" />
            <!-- <cmsTag @addTagsDataRelList="addTagsDataRelList" :itemId="itemId" :tagsDataRelList="person.tagList"></cmsTag> -->
            <el-form-item label='中文简介'>
              <el-input type="textarea" :maxlength="2000" :rows='4' v-model='person.cnDescription'></el-input>
            </el-form-item>
            <el-form-item label='英文简介'>
              <el-input type="textarea" :maxlength="2000" :rows='4' v-model='person.enDescription'></el-input>
            </el-form-item>
            <el-form-item label='备注'>
              <el-input type="textarea" :maxlength="2000" :rows='4' v-model='person.remark'></el-input>
            </el-form-item>
          </el-col>
        </el-row>   
      </el-form>
      <careerPortfolio></careerPortfolio>   
      <div class='m-t-20'>
       <incidenceRelation></incidenceRelation>
      </div>
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Watch } from 'vue-property-decorator';
import incidenceRelation from './incidence-relation/index.vue';
import careerPortfolio from './career-portfolio/index.vue';
import PersonService from '../../../service/subject/person';
import { PersonDto, PersonContactDto, ComTagDto } from '../../../api/Interface';
import logoImg from '../../../components/logo/index.vue';
import { getCascaderData, } from '../../../libs/utils';
import detailStateBtn from '../../../components/detail-state-btn/index.vue';
import cmsTag from '../../../components/cms-tag/index.vue';
import { StateMessage } from '../../../service/common/interface';
import { PersonSearchDto } from '../../../service/subject/person/personInterface';

interface InitView {
  sex: object[];
  personageTypes: object[];
  personEducation: object[];
}
@Component({
  components: { 
    incidenceRelation, // 关联关系
    careerPortfolio, // 职业履历
    logoImg, // 上传头像组件
    cmsTag,
    detailStateBtn,
  }
})

export default class CompanyList extends Vue {
  // 初始化数据 相当于data
   // 国家
  public areaList = getCascaderData({data: this.$store.state.user.dictionary.dicAreaList, name: 'cnName', key: 'id'});
  public area: number[] = [];
  public itemId: number = 0; // 业务id  人物id
  public person: PersonDto = {} as PersonDto; // <PersonDto> {}
  public personTypesList: number[] = [];
  public value: string = ' ';
  public quality: object[] = this.$store.state.csConst.checkType;
  public totalPage: number = 100; // 总页数
  public telCheck: boolean = false; // 电话验证的变量
  public mailCheck: boolean = false; // 邮箱验证的变量 
  public initView: InitView = {
    sex: this.$store.state.user.dictionary.dicList.personSex,
    personageTypes: this.$store.state.user.dictionary.dicList.personType,
    personEducation: this.$store.state.user.dictionary.dicList.personEducation,
  };
  public personSearch: PersonSearchDto = {} as PersonSearchDto;
  public comTagDtoList: ComTagDto[] = []; // 标签列表
  public tags: boolean;
  public cvIndustryValue: string[] = [];
  // 联系方式
  public personContactList: PersonContactDto = {} as PersonContactDto;
  public personContactsTel: PersonContactDto[] = [
    {
        contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
        contactType: 1,        //联系方式类型1手机2邮箱
        personId: 0,       //人物 id
        id: 0,
      },
  ]; //自定义联系方式  电话数组
  public personContactsMail: PersonContactDto[] = [ //制定会议联系方式 邮箱数组
    {
        contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
        contactType: 2,        //联系方式类型1手机2邮箱
        personId: 0,       //人物 id
        id: 0,
      },
  ]; 
  public photograph: string = '';
  public rules = {
      personTypes: [
          { required: true, message: '请选择人物类型', trigger: 'blur' },
      ],
      cnName: [
        { required: false, message: '不允许输入英文'},
        { validator: this.checkEnData, trigger: 'blur'},
      ],
      enName: [
        { required: false, message: '不允许输入中文'},
        { validator: this.checkCnData, trigger: 'blur'},
      ],
  };
  // refs
  public $refs: { 
    logoImg: any,
    basicForm: HTMLFormElement;
    tag: any
  };
  // watchwatch
  @Watch('personTypesList')
  public onChildChanged(val: string, oldVal: string) {
    // this.personTypesList.map((item: string) => {
    //   this.initView.personageTypes.map((i: object) => {
    //     if (i['dictName'] === item) {
    //         console.log(item)
    //     }
    //   })
    // });
  }
  // 声明周期钩子
  public mounted() {
    this.getMessage(); 
  }
  public created() {
    this.init();
  }
  // 方法
  public checkCnData(rule: object, value: string, callback: any) {  
    if (value) {
         if (/[\u4E00-\u9FA5]/g.test(value)) {
           callback(new Error('不允许输入汉字!'));
         } else {
           callback();
         }
       }
       callback();
  }
  public checkEnData(rule: object, value: string, callback: any) {
      if (value) {
        if (!/[\u4E00-\u9FA5]/g.test(value)) {
          callback(new Error('不允许输入英文!'));
        } else {
          callback();
        }
      }
      callback();
  }
  // 初始化
  public init() {
    if (!(this.$route.params.id === '-1')) {
      this.getPersonDetail();
    }
  }
// 中文名称模糊查询
  public async getSearchTitle(queryString: string, cb: any) {
      this.personSearch['pageParam.pageIndex'] = 1;
      this.personSearch['pageParam.pageSize'] = 100;
      this.personSearch.selectValue = queryString;
      this.personSearch.selectType = 'cn_name';
      const res = await PersonService.getPersonList(this.personSearch);
      if (res.resCode === '0') {
        const searchList = res.data.resultData;
        const result = searchList.map((item: any) => {
          return { value: item.cnName, id: item.id };
        });
        cb(result);
      }
  }
  // 模糊查询带出详情 
  public handleSelect(val: any) {
    this.$router.replace({name: 'person-detail', params: {id: val.id}});
    this.getPersonDetail();
  }
  // 获取详情
  public async getPersonDetail() {
    const data = await PersonService.getPersonDetail(this.$route.params.id);
    this.person = data;
    this.itemId = data.id;
    this.comTagDtoList = data.tagList; 
    // 人物类型
    this.person.personTypes.map( (item, index) => {
      this.personTypesList.push(item.personType);
    });
    // 国家
    this.area = [];
    this.area[0] = data.country;
    this.area[1] = data.province;
    if (data.city) {
       this.area[2] = data.city;
    }
    // if (this.area.length > 0) {
    //   this.flag = true;
    // }
    // 联系方式
    this.personContactsTel = [];
    this.personContactsMail = [];
    if (this.person.personContacts.length > 0) { // 有值
      this.person.personContacts.map( (item, index) => {
        if (item.contactType === 1) {
          this.personContactsTel.push(item);
        } else {
          this.personContactsMail.push(item);
        }
      });
    }
    if (!this.personContactsTel.length) {
      this.personContactsTel = [{
        contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
        contactType: 1,        //联系方式类型1手机2邮箱
        personId: Number(this.$route.params.id),       //人物 id
        id: 0,
      }];
    }
    if (!this.personContactsMail.length) {
      this.personContactsMail = [{
        contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
        contactType: 2,        //联系方式类型1手机2邮箱
        personId: Number(this.$route.params.id),       //人物 id
        id: 0,
      }];
    }
    
  }
  // 按钮
  public setState(state: StateMessage) {
    this.person.infoStatus = state.infoStatus;
    this.person.enableClick = Number(state.enableClick);
    this.person.enableCount = Number(state.enableCount);
    this.person.enableQuote = Number(state.enableQuote);
    this.person.publishMessage = state.publishMessage;
    this.savePersonDetailFun();
  }
  // 改变人物类型
  public changePersonType(val: number[]) {
    if (this.$route.params.id === '-1') {
      // 添加
      this.person.personTypes = [];
      val.map((item: number) => {
        this.person.personTypes.push({
          id: 0,
          personId: 0,
          personType: item
        });
      });
    } else {
      // 修改
      this.person.personTypes = [];
      val.map((item: number) => {
        this.person.personTypes.push({
          id: 0,
          personId: Number(this.$route.params.id),
          personType: item
        });
      });
    }
  }
  public delete() {
    this.getMessage();
  }
  // 编辑信息
  public edit() {
    this.getMessage();
  }
  public addPerson() {
    this.$router.push({name: 'person-add'});
  }
  // 当前页改变的时候
  public handleCurrentChange() {
    this.getMessage();
  }
  // 添加多个邮箱 
  public addMail() {
    if (this.$route.params.id === '-1') {
        this.personContactList = {
          contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
          contactType: 2,         //联系方式类型1手机2邮箱
          personId: 0,      //人物 id
          id: 0,
        };
    } else {
        this.personContactList = {
          contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
          contactType: 2,         //联系方式类型1手机2邮箱
          personId: Number(this.$route.params.id),         //人物 id
          id: 0,
        };
    }
    this.personContactsMail.push(Object.assign({}, this.personContactList));
  }
  // 删除邮箱
  public deleteMail(index: number) {
    this.personContactsMail.splice(index, 1);
  }
  // 添加多个电话 
  public addTel() {
    if (this.$route.params.id === '-1') {
        this.personContactList = {
          contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
          contactType: 1,         //联系方式类型1手机2邮箱
          personId: 0,      //人物 id
          id: 0,
        };
    } else {
        this.personContactList = {
          contactValue: '',        //联系方式内容(可能是手机号,可能是邮箱)
          contactType: 1,         //联系方式类型1手机2邮箱
          personId: Number(this.$route.params.id),         //人物 id
          id: 0,
        };
    }
    this.personContactsTel.push(Object.assign({}, this.personContactList));
  }
  // 删除电话
  public deleteTel(index: number) {
    this.personContactsTel.splice(index, 1);
  }
  public getMessage() {
    this.value = 'hahahh';
  }
  // 保存人物信息
  public async savePersonDetailFun() {
      this.$refs.logoImg.up();  
  }
  // 保存
  public savefunction() {
    // 中文 英文名称填写
      if (!this.person.cnName && !this.person.enName) {
          this.$message.warning('请填写中文名称或英文名称');
      } else if (this.person.cnName && !this.person.enName) {
          this.$message.warning('请填写英文名称');
      } else if (!(this.telCheck && this.mailCheck)) {
          this.$message.warning('请填写格式正确的手机号或邮箱');
      } else {
          this.$refs.basicForm.validate(async (valid: boolean) => {
          if (valid) {
              // 籍贯信息
              this.person.province = this.area[1];
              this.person.country = this.area[0];
              this.person.city = this.area[2] ? this.area[2] : 0;
              // 联系方式信息
              this.person.personContacts = this.personContactsTel.concat(this.personContactsMail);
              this.person.personContacts.map( (item, index) => {
                if (!item.contactValue) {
                  this.person.personContacts.splice(index, 1);
                }
              });
              const tagList = await this.$refs.tag.getTagList();
              this.person.tagList = tagList;
              if (this.$route.params.id === '-1') {
                  this.save();
              } else {
                  this.update();
              }
          }
        });
      }
  }
  public async save() {
    const res = await PersonService.savePerson(this.person);
    if (res.resCode === '0') {
      this.$message.success('保存成功');
      this.itemId = res.data;
      this.$router.replace({name: 'person-detail', params: {id: this.itemId.toString()}});
      // this.$route.replace({name: 'person-detail', params: {}})
      this.getPersonDetail();
    }
  }
    public async update() {
      const { resCode } = await PersonService.updatePerson(this.person);
      if (resCode === '0') {
        this.$message.success('修改成功');
      }
    }
    // 添加 的tag标签
   public addTagsDataRelList(val: any) {
        this.person.tagList = val;
    }
  // 标签验证
  public async tagPass(bool: boolean) {
      this.tags = bool;
      if (bool) {
          // this.testAll();
      } else {
          // this.$emit('testPass', false);
      }
  }
  public onSuccess(imgId: string) {
    if (imgId) {
        this.person.photograph = imgId;
    }
     this.savefunction();
  }
  // 关闭
  public close() {
      this.$router.push({name: 'person-list'});
  }
  // 
  public changeTel(list: any, val: string, index: number) {
      const arr: string[] = [];
      list.map(item => {
        if (val && !/^[1][3,4,5,7,8][0-9]{9}$/.test(item.contactValue)) {
          const txt = '第' + (index + 1) + '个手机号码有误!';
          arr.push('false');
          this.$message.warning(txt);
        } else {
          arr.push('true');
        }
      });
      if (arr.indexOf('false') === -1) {
          this.telCheck = true;
      }
  }
  public changeMail(list: any, val: string, index: number) {
    const arr1: string[] = [];
      list.map(item => {
        if (val && !/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(item.contactValue)) {
          const txt = '第' + (index + 1) + '个邮箱有误!';
          arr1.push('false');
          this.$message.warning(txt);
        } else {
          arr1.push('true');
        }
      });
      if (arr1.indexOf('false') === -1) {
          this.mailCheck = true;
      }
  }
  
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang='scss'>
.inline-block{
  display: inline-block;
}
</style>
